import {GetAjax} from "@lowcode/jpaas-common-lib";
var config={timeout:300000};
var rxAjax=GetAjax(config);

var FormUtil={};

/**
 * 客户端导出函数
 * @param url     导出的URL
 * @param params    传入的参数
 */
FormUtil.doExport=function (url,params){
    return new Promise(function (resolve, reject) {
        var config={responseType:"blob"};
        rxAjax.postJson(url,params,config).then(res=>{
            let data = res.data;
            let fileReader = new FileReader();
            fileReader.onload = function() {
                const blob = new Blob([data], {type: 'application/zip'});
                const filename = res.headers['content-disposition'];
                const downloadElement = document.createElement('a');
                const href = window.URL.createObjectURL(blob); //创建下载的链接
                downloadElement.href = href;
                var name=decodeURI(filename.split('=')[1].replace(/\"/g, "" ));
                downloadElement.download = name;
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放blob对
                resolve({success:true})
            };
            fileReader.readAsText(data);
        }).catch((error) => {
            resolve({success:false})
        });
    });
}

/**
 * 客户端导出函数
 * @param url     导出的URL
 * @param params    传入的参数
 */
FormUtil.doExport2=function (url,params){
    rxAjax.postJson(url,params,'blob').then(res=>{
        let data = res.data;
        let fileReader = new FileReader();
        fileReader.onload = function() {
            const blob = new Blob([data], {type: 'application/zip'});
            const filename = res.headers['content-disposition'];
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            var name=decodeURI(filename.split('=')[1].replace(/\"/g, "" ));
            downloadElement.download = name;
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放blob对
        };
        fileReader.readAsText(data)
    });
}

export default FormUtil;